package com.ruoyi.workflow.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.service.CommonService;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.workflow.domain.WfCopy;
import com.ruoyi.workflow.mapper.WfCopyMapper;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

/**
 * 全局监听-工作流待办消息提醒
 *
 * @author azhuzhu
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TaskCreate2Listener implements FlowableEventListener {

    private final CommonService commonService;
    private final TaskService taskService;
    private final WfCopyMapper copyMapper;
    private final HistoryService historyService;

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        TaskEntity taskEntity = (TaskEntity) ((FlowableEntityEventImpl) flowableEvent).getEntity();
        String taskId = taskEntity.getId();
        List<IdentityLink> idList = taskService.getIdentityLinksForTask(taskId);
        String historicProcessInstanceId = taskEntity.getProcessInstanceId();
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
            .processInstanceId(historicProcessInstanceId).singleResult();

        //抄送给管理员
        List<WfCopy> copyList = new ArrayList<>(1);
        Long originatorId = LoginHelper.getUserId();
        String originatorName = LoginHelper.getNickName();
        String title = historicProcessInstance.getProcessDefinitionName() + "-" + taskEntity.getName();
        Long uid = Long.valueOf(1);
        WfCopy copy = new WfCopy();
        copy.setTitle(title);
        copy.setProcessId(historicProcessInstance.getProcessDefinitionId());
        copy.setProcessName(historicProcessInstance.getProcessDefinitionName());
        copy.setDeploymentId(historicProcessInstance.getDeploymentId());
        copy.setInstanceId(historicProcessInstanceId);
        copy.setTaskId(taskId);
        copy.setUserId(uid);
        copy.setOriginatorId(originatorId);
        copy.setOriginatorName(originatorName);
        copyList.add(copy);
        copyMapper.insertBatch(copyList);

        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        List<String> userNameList = new ArrayList<>();
        // 获取接收人，此处从Identity获取，实际情况会更复杂
        idList.forEach(identityLink -> {
            if (StringUtils.isNotBlank(identityLink.getUserId())) {
                userNameList.add(identityLink.getUserId());
            }
        });

        String procInsId = taskEntity.getProcessInstanceId();

        if (CollectionUtils.isNotEmpty(userNameList)) {
            for (String userId : userNameList) {
                if (StringUtils.isNotEmpty(userId)) {
                    //发送提醒消息
                    String category = "";
                    if (taskService.getVariables(taskId).get("category") != null) {
                        category = taskService.getVariables(taskId).get("category").toString();
                    }

                    LoginUser loginUser = commonService.getLoginUser();
                    String taskMessageUrl =
                        "<a href=" + commonService.getBaseUrl() + procInsId + "?taskId=" + taskId + "&processed=true"
                            + ">点击这个进行处理</a>";
                    String msgContent = "流程待办通知" + taskMessageUrl;
//    	      		if(!StringUtils.equals(startUserId, receiver) || !StringUtils.equals((loginUser.getUserId()).toString(),receiver)) {//发起人或登录人自己不发送
                    log.info("流程待办通知给:" + userId);
                    try {
                        commonService.sendSysNotice(loginUser.getUserId(), userId, "流程待办通知",
                            msgContent, Constants.MSG_CATEGORY_3);//setMsgCategory=3是待办
                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                }
            }
        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}

